<template>
  <div class="container">
    <el-dialog
      :visible="visible"
      title="新增学科"
      width="400px"
      @close="closeHandler"
    >
      <el-form ref="form" :model="formData" :rules="formRules" size="small">
        <el-form-item label="学科名称" prop="subjectName" label-width="80px">
          <el-input
            v-model.trim="formData.subjectName"
            placeholder="请输入学科名称"
          />
        </el-form-item>
        <el-form-item prop="isFrontDisplay" label="是否显示" label-width="80px">
          <el-switch
            v-model="formData.isFrontDisplay"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-row type="flex" justify="end">
          <el-button @click="closeHandler">取消</el-button>
          <el-button type="primary" @click="submit">确认</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { add, detail, update} from "@/api/hmmm/subjects.js"
export default {
  name: "SubjectsAdd",
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      // 表单数据
      formData: {
        subjectName: "",
        isFrontDisplay: 1,
      },
      // 表单校验规则
      formRules: {
        subjectName: [{ required: true, message: "学科名称不能为空" }],
      },
    };
  },

  methods: {
    // 关闭弹窗
    closeHandler() {
      this.$refs.form.resetFields();
      this.formData = {
        subjectName: "",
        isFrontDisplay: 1,
      };
      this.$emit("update:visible", false);
    },
    // 提交表单数据
    async submit() {
      try {
        await this.$refs.form.validate();
        if (this.formData.id) {
          await update(this.formData);
          this.$message.success("修改学科成功");
          this.$emit("addSuccess");
        } else {
          await add(this.formData);
          this.$message.success("新增学科成功");
          this.$emit("addSuccess", "add");
        }
        this.closeHandler();
      } catch (error) {
        console.log(error);
      }
    },
    // 获取学科详细数据
    async getSubjectDetail(id) {
      try {
        const { data } = await detail({ id });
        this.formData = data;
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style scoped lang='scss'></style>
